﻿using _111.Models;
using _111.QywxDocument.DigitalizationDemand.Model;
using _111.QywxDocument.MeiTuanComment.Model;
using _111.QywxDocument.Model;
using _111.QywxDocument.PrivateRoom.Model;
using _111.QywxDocument.WeeklyReport.Model;
using guidHelper;
using MyDapperApi.Models;
using MyDapperApi.Services.QywxBase;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using System;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxDocument.PrivateRoom;
public class PrivateRoomService : IPrivateRoomService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly INetUpdateService _netUpdateService;
    private readonly INetDocumentService _netDocumentService;

    public PrivateRoomService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        ICsvService csvService,
        IQywxBaseService qywxBaseService,
        INetUpdateService netUpdateService,
        INetDocumentService netDocumentService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _qywxBaseService = qywxBaseService;
        _netUpdateService = netUpdateService;
        _netDocumentService = netDocumentService;
    }

    #region 拉取企业微信汇报表格-》数据库

    

    /// <summary>
    /// 获取记录内容详情
    /// </summary>
    /// <param name="recordId"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetRecordDetail(string recordId)
    {
        var result = new CommonResponse();

        var content1 = new
        {
            docid = "dcg-khAYWolnB_wv842q_7l83alf3SUWGTCz8cHl5bPgOxNT0FXrH-ftRssUi6PEO11xZVf0D1HCPDZS4qxyK_5Q",
            sheet_id = "q979lj",
            record_ids = new List<string>() { recordId },
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _qywxBaseService.QywxDocumentPost<SavePrivateRoomRecordDetail>(content, "https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_records?access_token=");

        if (wxResponse.records.Count > 0)
        {
            foreach (var item in wxResponse.records)
            {
                var current = string.Empty;
                
                var tempItem = new PrivateRoomEntity()
                {
                    Id = ToolHelper.GUIDTO16(),
                    Is_Deleted = 0,
                    Created_On = DateTime.Now,
                    Modified_On = DateTime.Now,
                    RecordId = item.record_id,
                    Private_Room = item.values.已预定餐包[0].text,
                    ShopName = item.values.门店名称[0].text,
                    Date = ToolHelper.ConvertMillisecondsToDateTimeString(long.Parse(item.values.日期)),
                };
                //CsvList.Add(tempItem);

                result = await CheckDateBase(tempItem);
            }

            return result;
        }

        return result;
    }

    /// <summary>
    /// 检查现有的数据条目
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> CheckDateBase(PrivateRoomEntity request)
    {
        var result = new CommonResponse();

        //var entity = new DocumentSafeRecordEntity();

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT *
                    FROM private_room WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND record_id = @RecordId ", "@RecordId", request.RecordId);

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<PrivateRoomEntity>(sql, sqlbuilder,0, "QywxDocument");

        if (entity != null)
        {
            request.Id = entity.Id;
            result = await SavePrivateRoomToDateBase(request, 1);
        }
        else
        {
            result = await SavePrivateRoomToDateBase(request, 0);
        }

        return result;
    }

    public async Task<CommonResponse>DeleteRecord(string recordId)
    {
        var result = new CommonResponse();

        var sqlbuilder = new SqlBuilder();
        var sql = @"UPDATE private_room
SET        
    is_deleted = 1
WHERE 
    record_id = @RecordId; ";
        sqlbuilder.Add("", "@RecordId",recordId);

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder, 0, "QywxDocument");

        return result;
    }

    /// <summary>
    /// 保存基础数据到数据库
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SavePrivateRoomToDateBase(PrivateRoomEntity request, int type)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", request.Id);
        sqlbuilder.Add("", "@IsDeleted", request.Is_Deleted);
        sqlbuilder.Add("", "@RecordId", request.RecordId);
        sqlbuilder.Add("", "@ShopName", request.ShopName);
        sqlbuilder.Add("", "@Date", request.Date);
        sqlbuilder.Add("", "@Private_Room", request.Private_Room);

        if (type == 0)
        {
            sql = @$"INSERT INTO private_room (
    id, 
    record_id,
    created_on, 
    is_deleted, 
    shop_name, 
    date,
    private_room
) VALUES (
    @Id, 
    @RecordId,
    @CreatedOn, 
    @IsDeleted, 
    @ShopName, 
    @Date,
    @Private_Room
);";
            sqlbuilder.Add("", "@CreatedOn", request.Created_On);
        }
        else
        {
            sql = $@"UPDATE private_room
SET 
    modified_on = @ModifiedOn,        
    is_deleted = 0,        
    shop_name = @ShopName,    
    date = @Date,
    private_room = @Private_Room
WHERE 
    id = @Id;";
            sqlbuilder.Add("", "@ModifiedOn", request.Modified_On);
        }

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder, 0, "QywxDocument");

        return result;
    }

    #endregion
}